package edu.upc.clase.demo.dao.impl;
    import edu.upc.clase.demo.dao.SalaDao;
    import edu.upc.clase.demo.entity.Sala;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class SalaDaoImpl extends SimpleJdbcDaoSupport implements SalaDao{
    
    private static Logger log = LoggerFactory.getLogger(SalaDaoImpl.class);
    
    @Autowired
    public SalaDaoImpl(DataSource dataSource) {
        log.info("Asignando el dataSource");
        setDataSource(dataSource);
    }
    
    @Override
    public Integer insertarSala(Sala objSala){
        try{
            getJdbcTemplate().update(
                "INSERT INTO sala(nombresala, capacidad, caracteristicasala, local_idlocal) values (?, ?, ?, ?)",
                objSala.getNombre(), objSala.getCapacidad(), objSala.getCaracteristica(), objSala.getIdLocal());
            return getSimpleJdbcTemplate().queryForInt("select last_insert_id()");
        }catch(ExceptionInInitializerError e){
            return null;
        }
        
        
    }
    
    @Override
    public void modificarSala(Sala objSala){
        getJdbcTemplate().update(
                "UPDATE sala SET nombresala = ?,  capacidad = ?, caracteristicasala = ?, local_idlocal = ? WHERE idSala = ?",
                objSala.getNombre(), objSala.getCapacidad(), objSala.getCaracteristica(), objSala.getIdLocal(), objSala.getIdSala());
    }
    @Override
    public void eliminarSala(Integer idSala){
        getJdbcTemplate().update(
                "DELETE FROM sala WHERE idSala = ?",
                idSala);
    }
            
    @Override
    public List<Sala> BuscarTodos(){
        return getSimpleJdbcTemplate().query(
                "SELECT idsala , nombresala, capacidad, caracteristicasala, local_idlocal FROM sala",
                new BeanPropertyRowMapper<Sala>(Sala.class));
    }
    
    @Override
    public List<Sala> BuscarNombre(String nombre){
        try {
            Map<String,String> parametros = new HashMap<String,String>();
            parametros.put("nombre","%"+nombre+"%");
            return getSimpleJdbcTemplate().query(
                    "SELECT idsala , nombresala, capacidad, caracteristicasala, local_idlocal FROM sala WHERE nombresala like :nombre",
                    new BeanPropertyRowMapper<Sala>(Sala.class),parametros);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    
    /// --------
        
}
